package org.example.controller;

import org.example.entity.User;
import org.example.exception.AccountExitException;
import org.example.exception.PassWordException;
import org.example.service.UserService;
import org.example.service.RedisService;
import org.example.vo.RegisterVo;
import org.example.utils.PasswordUtils;
import org.example.utils.R;
import org.example.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    UserService userService;
    @Autowired
    RedisService redisService;

    @RequestMapping("/login")
    public @ResponseBody R parentLogin(@RequestParam String account, @RequestParam String password, HttpServletResponse httpServletResponse) throws AccountExitException, PassWordException {
        User user = userService.getUserByAccount(account);
        if(user==null) throw new AccountExitException();
        if(!PasswordUtils.isMatch(password, user.password)){
            throw new PassWordException();
        }
        //登入成功
        String token = TokenUtils.getToken();
        httpServletResponse.addHeader("token",token);
        redisService.setUser(token,user);
        //删除老的token和User信息
        redisService.deleteToken(user.id);
        //设置新的token
        redisService.setToken(user.id, token);
        return R.ok().setData(null);
    }



    @PostMapping("/register")
    public  @ResponseBody R register(@RequestBody RegisterVo registerVo) throws AccountExitException {
        userService.createUser(registerVo,0);
        return R.ok().setData(null);
    }



}
